package com.ptbuy.utils;

import android.app.ProgressDialog;
import android.content.Context;

import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.HorizontalAlignment;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.UnitValue;
import com.ptbuy.callback.ExportMsgCall;
import com.ptbuy.db.dao.ExportDao;
import com.ptbuy.db.pojo.ProductPojo;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

public class ExportUtils {

    //导出PDF
    public static void exportPDF(List<ProductPojo> recodInfos, String singaturePath, Context context, String mytotalProduct, String mytotalPrice, ExportMsgCall exportMsgCall) {
        // 获取外部存储目录
        ProgressDialog progressDialog = new ProgressDialog(context);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("正在导出");
        progressDialog.setCancelable(false);
        progressDialog.show();
        new Thread(() -> {

            String currentTime = Utils.getCurrentTime(new Date());
            String filePath = Constants.getExportFilePath() + currentTime + ".pdf";
            File pdfDir = new File(Constants.getExportFilePath());
            if (!pdfDir.exists()) {
                pdfDir.mkdirs();
            }

            // PDF 文件路径
            File file = new File(pdfDir, currentTime + ".pdf");
            Document document = null;
            try {
                PdfWriter writer = new PdfWriter(file.getAbsolutePath());
                PdfDocument pdfDoc = new PdfDocument(writer);
                document = new Document(pdfDoc, PageSize.A4);

                // 加载支持中文的字体
                PdfFont font = PdfFontFactory.createFont("assets/Y-B008YeZiGongChangDanDanHei-2.ttf", PdfEncodings.IDENTITY_H, true);


                /**
                 * -=------------------2024年10月12日17:04:35设置标题，需要测试
                 */
                Table tableTitle = new Table(UnitValue.createPercentArray(1)).useAllAvailableWidth(); // 假设每行有 3 列
                tableTitle.addHeaderCell(new Cell().add(new Paragraph("二手奢侈品交易确认单").setFont(font)).setFontSize(20).setTextAlignment(TextAlignment.CENTER).setBorder(null));
                // 设置标题
                document.add(tableTitle);

                Table table = new Table(UnitValue.createPercentArray(7)).useAllAvailableWidth(); // 假设每行有 3 列

                // 添加表头
                table.addHeaderCell(new Cell().add(new Paragraph("序号").setFont(font)).setWidth(10).setFontSize(10).setTextAlignment(TextAlignment.CENTER));
                table.addHeaderCell(new Cell().add(new Paragraph("名称").setFont(font)).setWidth(20).setFontSize(10).setTextAlignment(TextAlignment.CENTER));
                table.addHeaderCell(new Cell().add(new Paragraph("价格").setFont(font)).setWidth(10).setFontSize(10).setTextAlignment(TextAlignment.CENTER));
                table.addHeaderCell(new Cell().add(new Paragraph("记录时间").setFont(font)).setWidth(20).setFontSize(10).setTextAlignment(TextAlignment.CENTER));
                table.addHeaderCell(new Cell().add(new Paragraph("客户名称").setFont(font)).setWidth(20).setFontSize(10).setTextAlignment(TextAlignment.CENTER));
                table.addHeaderCell(new Cell().add(new Paragraph("收购人").setFont(font)).setWidth(10).setFontSize(10).setTextAlignment(TextAlignment.CENTER));
                table.addHeaderCell(new Cell().add(new Paragraph("客户电话").setFont(font)).setWidth(20).setFontSize(10).setTextAlignment(TextAlignment.CENTER));
//                table.addHeaderCell(new Cell().add(new Paragraph("照片").setFont(font)).setWidth(10).setFontSize(10).setTextAlignment(TextAlignment.CENTER));

                int sum = 1;
                // 添加商品列表
                for (ProductPojo product : recodInfos) {
//                ProductPojo product = recodInfos.get(0);
                    //设置字体
                    table.addCell(new Cell().add(new Paragraph(String.valueOf(sum)).setFont(font)).setTextAlignment(TextAlignment.CENTER)); // Product Name
                    sum++;
                    table.addCell(new Cell().add(new Paragraph(String.valueOf(product.getProductName())).setFont(font)).setTextAlignment(TextAlignment.CENTER)); // Price
                    String productPrice = product.getProductPrice();


                    String dealPrice = Utils.getNumlStr(productPrice);

                    table.addCell(new Cell().add(new Paragraph(dealPrice + "元").setFont(font)).setTextAlignment(TextAlignment.CENTER)); // Price
                    String time = product.getTime();
                    String s = Utils.stringToTime(time);
                    table.addCell(new Cell().add(new Paragraph(String.valueOf(s)).setFont(font).setTextAlignment(TextAlignment.CENTER))); // Price

                    String name = product.getClientPojo().getName();
                    if (name == null) {
                        name = "";
                    }
                    table.addCell(new Cell().add(new Paragraph(name).setFont(font).setTextAlignment(TextAlignment.CENTER))); // Price
                    String agentName = String.valueOf(product.getClientPojo().getAgentName());
                    if (agentName == null) {
                        agentName = "";
                    }
                    table.addCell(new Cell().add(new Paragraph(agentName).setFont(font).setTextAlignment(TextAlignment.CENTER))); // Price
                    String phone = String.valueOf(product.getClientPojo().getPhone());
                    if (phone == null) {
                        phone = "";
                    }
                    /**
                     * -=------------------2024年10月12日17:04:35合并单元格，需要测试
                     */
                    table.addCell(new Cell().add(new Paragraph(phone).setFont(font).setTextAlignment(TextAlignment.CENTER))); // Price

//                    table.addCell(new Cell().add(new Paragraph(String.valueOf(product.getMult())).setFont(font)).setWidth(10).setFontSize(10).setTextAlignment(TextAlignment.CENTER)); // Price
                }

                table.addCell(new Cell(1, 7).add(new Paragraph("总件数: " + mytotalProduct + "          总价：" + mytotalPrice + "元").setFont(font).setTextAlignment(TextAlignment.CENTER))); // Price

                // 添加一些空白行以分隔签名
                document.add(new Paragraph("\n")); // 添加空白行

                document.add(table);

//                document.add(new Paragraph("总件数: " + mytotalProduct + "          总价：" + mytotalPrice).setFontColor(ColorConstants.BLACK).setFont(font).setTextAlignment(TextAlignment.CENTER));

                // 添加一些空白行以分隔签名
                document.add(new Paragraph("\n")); // 添加空白行


                String currentTime1 = Utils.getCurrentTime(new Date());
                String s = Utils.stringToTime(currentTime1);
                //                // 在表格下方添加签名

                if (singaturePath == null) {
                    document.add(new Paragraph("客户签名: __________").setFontColor(ColorConstants.BLACK).setFont(font).setTextAlignment(TextAlignment.RIGHT));
                } else {
                    // 创建一个表格，右侧放置签名区域
                    Table table1 = new Table(2);
                    table1.setHorizontalAlignment(HorizontalAlignment.RIGHT);
                    table1.addCell(new Cell().add(new Paragraph("客户签名:")).setFontColor(ColorConstants.BLACK).setFont(font).setTextAlignment(TextAlignment.RIGHT).setBorder(null));
                    // 添加图片
                    Image img = new Image(ImageDataFactory.create(singaturePath));
                    img.scaleToFit(50, 100);
                    // 右侧签名区域
                    Cell signatureCell = new Cell().add(img).setBorder(null);
                    signatureCell.setHorizontalAlignment(HorizontalAlignment.RIGHT);
                    table1.addCell(signatureCell);
                    document.add(table1);
                }
                document.add(new Paragraph(s).setFontColor(ColorConstants.BLACK).setFont(font).setTextAlignment(TextAlignment.RIGHT));


                ExportDao exportDao = new ExportDao();
                exportDao.delInfoByclientid(recodInfos.get(0).getPid());
                exportDao.addInfo(filePath, recodInfos.get(0).getPid());
                exportMsgCall.exportFile(filePath);


            } catch (Exception e) {
                e.printStackTrace();
                exportMsgCall.exportFile(null);
            } finally {
                progressDialog.dismiss();
                if (document != null) {
                    document.close();
                }
            }
        }).start();
    }

    //导出Excel
    public static void exportExcel(List<ProductPojo> recodInfos, Context context, ExportMsgCall exportMsgCall) {

        ProgressDialog progressDialog = new ProgressDialog(context);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("正在导出");
        progressDialog.setCancelable(false);
        progressDialog.show();
        new Thread(() -> {
            FileOutputStream fileOutputStream = null;
            try {
                System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
                // 创建工作簿
                Workbook workbook = new XSSFWorkbook();

                // 创建工作表
                Sheet sheet = workbook.createSheet("二手奢侈品交易确认单");

                // 创建列名行
                Row headerRow = sheet.createRow(0);
                headerRow.createCell(0).setCellValue("ID");
                headerRow.createCell(1).setCellValue("名称");
                headerRow.createCell(2).setCellValue("价格");
                headerRow.createCell(3).setCellValue("记录时间");
                headerRow.createCell(4).setCellValue("客户名称");
                headerRow.createCell(5).setCellValue("收购人");
                headerRow.createCell(6).setCellValue("客户电话");
                headerRow.createCell(7).setCellValue("照片路径");

                int sum = 1;
                for (int i = 0; i < recodInfos.size(); i++) {
                    // 创建数据行
                    Row dataRow = sheet.createRow(1 + i);
                    dataRow.createCell(0).setCellValue(sum);
                    sum++;
                    dataRow.createCell(1).setCellValue(recodInfos.get(i).getProductName());
                    String productPrice = recodInfos.get(i).getProductPrice();
                    String dealPrice = Utils.getNumlStr(productPrice);

                    dataRow.createCell(2).setCellValue(dealPrice + "元");
                    dataRow.createCell(3).setCellValue(recodInfos.get(i).getTime());
                    String name = recodInfos.get(i).getClientPojo().getName();
                    if (name == null) {
                        name = "";
                    }
                    dataRow.createCell(4).setCellValue(name);
                    String agentName = recodInfos.get(i).getClientPojo().getAgentName();
                    if (agentName == null) {
                        agentName = "";
                    }
                    dataRow.createCell(5).setCellValue(agentName);
                    String phone = recodInfos.get(i).getClientPojo().getPhone();
                    if (phone == null) {
                        phone = "";
                    }
                    dataRow.createCell(6).setCellValue(phone);
                    String mult = recodInfos.get(i).getMult();
                    if (mult == null) {
                        mult = "";
                    }
                    dataRow.createCell(7).setCellValue(mult);
                }

                sheet.addMergedRegion(new CellRangeAddress(
                        1 + recodInfos.size(), // 起始行
                        1 + recodInfos.size(), // 结束行
                        0, // 起始列
                        7  // 结束列
                ));
                Long totalPrice = 0L;
                for (int k = 0; k < recodInfos.size(); k++) {
                    totalPrice += Long.parseLong(recodInfos.get(k).getProductPrice().replace(",", ""));
                }

                String dealPrice = Utils.getNumlStr(totalPrice.toString());

                Row dataRow = sheet.createRow(recodInfos.size() + 1);
                dataRow.createCell(0).setCellValue("总件数：" + recodInfos.size() + "件；总价格：" + dealPrice + "元");

                // 获取手机存储路径
                String currentTime = Utils.getCurrentTime(new Date());
                String filePath = Constants.getExportFilePath() + currentTime + ".xlsx";


                // 创建文件输出流
                fileOutputStream = new FileOutputStream(filePath);

                // 写入数据到文件中
                workbook.write(fileOutputStream);
                ExportDao exportDao = new ExportDao();
                exportDao.delInfoByclientid(recodInfos.get(0).getPid());
                exportDao.addInfo(filePath, recodInfos.get(0).getPid());
                exportMsgCall.exportFile(filePath);


            } catch (IOException e) {
                e.printStackTrace();
                exportMsgCall.exportFile(null);
            } finally {
                progressDialog.dismiss();
                try {
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                } catch (Exception e) {

                }
            }
        }).start();
    }
}
